// 云函数入口文件
const cloud = require('wx-server-sdk')
const jwt = require('jsonwebtoken')
global.navigator = {
  userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1'
}
global.window = {
  ASN1: null,
  Base64: null,
  Hex: null,
  crypto: null,
  href: null
};
const {
  JSEncrypt
} = require('encryptlong')

const secret = 'zeyi';
const PRIVATE_KEY = '-----BEGIN RSA PRIVATE KEY-----MIICXAIBAAKBgQCnDmfaCe4t0wvg4lxiVLIZ1QThCsSALbsF3ILAEugn78jYGct0DJ3QLx4xlDTUvTIyUQsissin41245qR9gkamKFNc77t4lVaV/8hChyF0M/UtdN9T7szcjbO17S+xqNRS9rwWmT4PDETXNe+EYIMUI+/0c+BXlpkA0loMlqd1zQIDAQABAoGBAKP2NKHBK18Yi8kOAsSUAjXuaJqD2fdAaxZGpqHkLK293++R6akeFOpWxJi+sNe4VgMinf5RYTW+p6cp4Ho7GiC28Y4VsFWCExiRisgvAokKPozx7g4JfZzSQytqYn+OCXM83Oxk/a9XUz8CQdd88tpXPatv3uo9kxGHoToefg11AkEA0BP35iGuj0exUAtHEmqdjhBi4RL9u0iOo/SrHfNT3xBhg523YjlOO+TG9oAz3XuC+4O+RGBC1cPRCZM+k499mwJBAM2H2Ex/WIfjdkDWJfliwS9q03uDRAC+ElF+o/pwKD+LAF5/gTMiRFOB0Nd++PVjFYBpHNLJbSxNF9ST92BexLcCQFW/5Olx9/4UDX5vJ1rvlP52wkj/CpGj1SS8L8in/mhu18Dlvi08cIE+RsBPFRCxVclRAZgsE18E06CejatB9wECQGfBOBQGBW80CLJaaPkoPVXum6wya9XkHeM+BxGaJPdO+HS78UEa/1sYoZDn7E4UIvqcFYzjWlWO5YTO3Yas0KkCQEF7Ra4L/3rntkaNEQnRM+3t1U79YwPCDXbfw7M1Bg/fsWX4jPyagUcmo+S19/5Y2vFsDc2/EFu4M+JuMYCaDhk=-----END RSA PRIVATE KEY-----'

const PUBLIC_KEY = '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnDmfaCe4t0wvg4lxiVLIZ1QThCsSALbsF3ILAEugn78jYGct0DJ3QLx4xlDTUvTIyUQsissin41245qR9gkamKFNc77t4lVaV/8hChyF0M/UtdN9T7szcjbO17S+xqNRS9rwWmT4PDETXNe+EYIMUI+/0c+BXlpkA0loMlqd1zQIDAQAB-----END PUBLIC KEY-----'

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

// 云函数入口函数
exports.main = async(event, context) => {
  let enc = new JSEncrypt()
  // 使用设置公私钥
  enc.setPublicKey(PUBLIC_KEY)
  enc.setPublicKey(PRIVATE_KEY)

  if (event.type == 'encode') {
    //获取token
    let payload = {
      groupId: event.groupId
    };
    let token = jwt.sign(payload, secret, {
      expiresIn: 60 * 60
    }); //有效期一小时
    //对token加密
    return enc.encryptLong(token)
  } else if (event.type == 'decode') {
    var decoded = null;
    try {
      let token = enc.decryptLong(event.token)
      decoded = jwt.verify(token, secret)
    } catch (error) {}
    return decoded
  }
}